<template lang="pug">
.content
  .card
    .card-header(data-background-color='blue')
      h4.title {{title}}
      p.category 请填写以下设备信息
    .card-content
      form
        .row
          .col-md-6
            md-fg-input(label='ICCID', :labelFloating='!deviceId', v-model='device.iccid')
          .col-md-6
            md-fg-input(label='用户 ID', :labelFloating='!deviceId', v-model='device.userid')
        .row
          .col-md-6
            md-fg-input(label='安装地点', :labelFloating='false', v-model='device.address')
          .col-md-6
            md-fg-input(type='date', label='安装日期', :labelFloating='false', v-model='device.installAt')
        .row
          .col-md-12
            md-fg-input(type='textarea', label='备注', :labelFloating='!deviceId', :rows='5', v-model='device.misc')
        md-button.btn.btn-primary.pull-right(@click.prevent='save') 保存
        .clearfix
</template>
<script>
import axios from 'axios'
export default {
  data() {
    return {
      device: {
        iccid: '',
        userid: '',
        address: '',
        installAt: new Date(),
        misc: ''
      }
    }
  },
  computed: {
    deviceId() {
      return this.$route.params.id
    },
    title() {
      return this.deviceId ? '更改设备' : '新增设备'
    }
  },
  methods: {
    save() {
      if (this.deviceId) {
        axios.put(process.env.API_URL + '/ysj/id/' + this.deviceId, this.device)
        .then((response) => this.$router.push({path: '/devices'}))
        .catch((error) => console.log(error))
      } else {
        axios.post(process.env.API_URL + '/ysj', this.device)
        .then((response) => this.$router.go(-1))
        .catch((error) => console.log(error))
      }
    }
  },
  created() {
    if (this.deviceId) {
      axios.get(process.env.API_URL + '/ysj/id/' + this.deviceId)
      .then(res => {
        this.device = res.data
      })
      .catch((error) => console.log(error))
    }
  }
}
</script>

